#include <iostream>
#include "log.hpp"
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string>
// 服务器 实现对于客户端的接发消息
// 策略 UDP协议 sokct = IP + port 套接字

int main(int args, char *argv[])
{
    if (args != 3)
    {
        logMessage(FATAL, "args != 3");
        exit(1);
    }

    int sock = socket(AF_INET, SOCK_DGRAM, 0);
    if (sock < 0)
    {
        exit(2);
    }

    struct sockaddr_in server;
    uint16_t server_port = atoi(argv[2]);
    server.sin_family = AF_INET;
    server.sin_port = htons(server_port);
    server.sin_addr.s_addr = inet_addr(argv[1]);

    std::string message;
    char buffer[1024];
    while (true)
    {
        std::cout << "请输入消息：";
        std::getline(std::cin, message);
        if (message == "quit")
        {
            break;
        }
        // 第一次向服务器发送消息的时候OS会自动分配prot和IP
        sendto(sock, message.c_str(), message.size(), 0, (struct sockaddr *)&server, sizeof server);

        // 接收消息
        struct sockaddr_in temp;
        socklen_t len = sizeof temp;
        ssize_t s = recvfrom(sock, buffer, sizeof(buffer), 0, (struct sockaddr *)&temp, &len);
        if (s > 0)
        {
            buffer[s] = 0;
            std::cout << "server echo: " << buffer << std::endl;
        }
    }

    return 0;
}